package transfer;

import java.io.*;
import java.time.LocalDateTime;

/**
 * @author yangwenqi
 * @decs TODO
 * @date 2025/5/14

 */
public class LoginTest2 {
    public static void login(String username, String password) {
        try (PrintStream infoPs = new PrintStream(new FileOutputStream("info.log",true));
             PrintStream errorPs = new PrintStream(new FileOutputStream("error.log",true));
             //获取与指定的类同级目录下的流对象
             InputStream is = LoginTest.class.getResourceAsStream("emp.txt");
             InputStreamReader isr = new InputStreamReader(is);
             BufferedReader br = new BufferedReader(isr)) {
            // 读取用户信息并验证
            boolean flag = false;
            String s;
            while ((s = br.readLine()) != null) {
                String[] userInfo = s.split("#");
                if (username.equals(userInfo[0])
                        && password.equals(userInfo[1])) {
                    flag = true;
                    break;
                }
            }
            // 根据验证结果输出日志
            if (flag) {
                System.setOut(infoPs);  // 重定向标准输出到info日志
                System.out.println(LocalDateTime.now() + " 登录成功 : 用户：" + username);
            } else {
                System.setErr(errorPs); // 重定向标准错误到error日志
                System.err.println(LocalDateTime.now() + " 登录失败 : 用户：" + username + "  密码或账号错误！");
            }

        }catch (Exception e){
            System.err.println(LocalDateTime.now()+"出现异常："+e.getMessage());
        }
    }

    public static void main(String[] args) {
        login("李四", "123");
        login("张三", "111");
        login("王五", "333");
    }
}
